#include "../include/server.h"
#include <errno.h>

int main()
{
	int socket_id = -1;
	
	/*初始化套接字描述符，绑定地址，建立监听队列*/
	socket_id = socket_init(PORT, IP);
	if(0 > socket_id)
	{
		puts("socket_init error");
		return -1;
	}
	
	/*初始化epoll使用的结构体和结构体数组*/
	struct epoll_event ev, events[MAX_EVENTS];
	int epollfd = 0;
	
	/*初始化监听链表*/
	epollfd = epoll_create(100);
	if(-1 == epollfd)
	{
		puts("epoll_create error");
		close(socket_id);
		return -1;
	}
	
	/*设置触发方式为可读*/
	ev.events = EPOLLIN;

	ev.data.fd = socket_id;
	
	/*将监听套接字放入epoll监听链表中*/
	if(0 > epoll_ctl(epollfd, EPOLL_CTL_ADD, socket_id, &ev))
	{
		perror("epoll_ctl");
		close(socket_id);
		close(epollfd);
		return -1;
	}
	
	while(1)
	{
		/*等待epoll监听链表中文件状态的变化*/
		int ret = epoll_wait(epollfd, events, MAX_EVENTS, -1);
		if(0 > ret)
		{
			if(errno == EINTR)
			{
				continue;
			}
			perror("epoll_wait");
			break;
		}
		
		/*循环处理事件*/
		for(int i = 0; i < ret; i++)
		{
			if(socket_id == events[i].data.fd)
			{
				accept_link(socket_id, epollfd);
			}
			else
			{
				communication(events[i].data.fd, epollfd);
			}
		}
	}

	close(socket_id);
	close(epollfd);
	return 0;
}
